package com.xxl.api.admin;

import com.xxl.api.admin.core.model.XxlApiMock;
import com.xxl.api.admin.dao.IXxlApiProjectDao;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class MockApiFilter implements Filter {

    @Resource
    private IXxlApiProjectDao xxlApiProjectDao;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * 过滤后的处理操作
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        String projectName = "";
        String requestUrl = "";
        if (requestURI != null && requestURI.startsWith("/mockapi")) {
            requestUrl = requestURI.substring(9);
            projectName = requestUrl.substring(0, requestUrl.indexOf("/"));
            requestUrl = requestUrl.substring(requestUrl.indexOf("/"));
            XxlApiMock xxlApiMock = xxlApiProjectDao.getXxlApiMock(projectName, requestUrl);
            String newPath = "/mock/run/" + xxlApiMock.getUuid();
            request.getRequestDispatcher(newPath).forward(request, response);
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
